package elijah.base.widget;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.LinearGradient;
import android.graphics.Shader;
import android.util.AttributeSet;
import android.view.ViewTreeObserver;

import androidx.annotation.Nullable;
import androidx.appcompat.widget.AppCompatTextView;

import elijah.base.R;


public class GradientText extends AppCompatTextView {
    private int startColor;
    private int endColor;
    private int mode;

    public GradientText(Context context) {
        this(context, null);
    }

    public GradientText(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public GradientText(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        if (attrs != null) {
            TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.GradientText);
            startColor = typedArray.getColor(R.styleable.GradientText_start_color, getCurrentTextColor());
            endColor = typedArray.getColor(R.styleable.GradientText_end_color, getCurrentTextColor());
            mode = typedArray.getInt(R.styleable.GradientText_mode, 0);
            typedArray.recycle();
        }

        getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                getPaint().setShader(new LinearGradient(0, 0, 0, mode == 2 ? getHeight() / 2f : getHeight(),
                        startColor, endColor, mode == 2 ? Shader.TileMode.MIRROR : Shader.TileMode.CLAMP));
                getViewTreeObserver().removeOnGlobalLayoutListener(this);
            }
        });
    }


}

